<template>
  <div class="page-field login">
    <div class="page-title">
      注册
    </div>

    <div class="page-part form-body">
      <mt-field label="用户名" placeholder="请输入手机号或邮箱" type="text" v-model="username"></mt-field>
      <mt-field label="昵称" placeholder="请输入昵称" type="nickname" v-model="nickname"></mt-field>
      <mt-field label="密码" placeholder="请输入密码" type="password" v-model="password"></mt-field>
      <mt-field label="确认密码" placeholder="确认密码" type="password_verify" v-model="password_verify"></mt-field>
    </div>

    <div class="page-part form-button">
      <mt-button type="primary" class="form-submit" v-on:click="register()" v-bind:disabled="!checkUsernameAndPass()">注册</mt-button>
      <mt-button type="default" v-on:click="login()">登陆</mt-button>
    </div>
  </div>
</template>

<script>
import axios from 'axios';
import { Toast } from 'mint-ui';
import qs from 'qs';

export default {
  name: 'register',
  data() {
    return {
      username: '',
      nickname: '',
      password: '',
      password_verify: '',
    };
  },
  methods: {
    register() {
      axios.post('/user/register', qs.stringify({
        username: this.username,
        nickname: this.nickname,
        password: this.password,
        password_verify: this.password_verify,
      })).then((response) => {
        if (response.status === 200) {
          if (response.data.status === true) {
            Toast({
              message: '注册成功,请登陆',
              duration: 1500,
            });
            setTimeout(() => {
              this.$router.push({
                name: 'Login',
              });
            }, 1500);
          } else {
            let error = '';
            const errorDatas = Object.entries(response.data.data);
            errorDatas.forEach((item) => {
              const [key, value] = item;
              error += key + value;
            });
            Toast({
              message: error,
              duration: 1500,
            });
          }
        }
      }).catch((err) => {
        Toast({
          message: err,
          duration: 1500,
        });
      });
    },
    login() {
      this.$router.push({
        name: 'Login',
      });
    },
    checkUsernameAndPass() {
      return (this.username !== '' && this.nickname !== ''
       && this.password !== '' && this.password_verify === this.password
      );
    },
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
a {
  color: #42b983;
}

.form-button {
  margin-top: 20px;
}

.form-submit {
  margin-right: 40px;
}

.form-body {
  margin-top: 20px;
}
</style>
